/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 启动页面 - 处理应用初始化和权限检查
 */

import 'package:flutter/material.dart';
import '../services/permission_manager.dart';
import '../services/floating_ui_manager.dart';
import 'permission_check_page.dart';
import '../main.dart';

/// 启动页面
class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;

  final bool _isInitializing = true;
  String _initializationStatus = '正在初始化...';

  @override
  void initState() {
    super.initState();
    _setupAnimations();
    _initializeApp();
  }

  /// 设置动画
  void _setupAnimations() {
    _animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));

    _scaleAnimation = Tween<double>(
      begin: 0.5,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.elasticOut,
    ));

    _animationController.forward();
  }

  /// 初始化应用
  Future<void> _initializeApp() async {
    try {
      // 显示启动动画
      await Future.delayed(const Duration(milliseconds: 500));

      if (mounted) {
        setState(() {
          _initializationStatus = '检查权限...';
        });
      }

      // 初始化权限检查
      // final permissionResult =
      //     await PermissionManager.instance.initializePermissions();

      if (mounted) {
        setState(() {
          _initializationStatus = '准备就绪';
        });
      }

      // 等待动画完成
      await Future.delayed(const Duration(milliseconds: 500));

      if (!mounted) return;
      _navigateToHome();
      //   // 根据权限检查结果决定跳转
      //   if (permissionResult.hasAllPermissions) {
      //     // 权限已授予，直接进入主页
      //     _navigateToHome();
      //   } else if (permissionResult.hasError) {
      //     // 权限检查出错，直接进入主页（确保用户能正常使用应用）
      //     debugPrint('SplashPage: 权限检查出错，直接进入主页');
      //     _navigateToHome();
      //   } else {
      //     // 需要请求权限，跳转到权限检查页面
      //     _navigateToPermissionCheck();
      //   }
    } catch (error) {
      debugPrint('SplashPage: 初始化失败 - $error');
      if (mounted) {
        setState(() {
          _initializationStatus = '初始化失败';
        });

        // 显示错误后跳转到权限检查页面
        await Future.delayed(const Duration(seconds: 2));
        if (mounted) {
          _navigateToPermissionCheck();
        }
      }
    }
  }

  /// 跳转到主页
  void _navigateToHome() {
    if (!mounted) return;
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        builder: (context) => const FloatingPlayerInitializer(
          config: FloatingPlayerConfig(
            initialPosition: FloatingPlayerPosition.bottomRight,
            enableRotation: true,
            backgroundColor: Color(0x80000000),
          ),
          child: HomePage(),
        ),
      ),
    );
  }

  /// 跳转到权限检查页面
  void _navigateToPermissionCheck() {
    if (!mounted) return;
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        builder: (context) => PermissionCheckPage(
          onPermissionGranted: _navigateToHome,
          onSkip: _navigateToHome,
        ),
      ),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          return FadeTransition(
            opacity: _fadeAnimation,
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // 应用图标
                  ScaleTransition(
                    scale: _scaleAnimation,
                    child: Container(
                      width: 120,
                      height: 120,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(24),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.2),
                            blurRadius: 20,
                            offset: const Offset(0, 10),
                          ),
                        ],
                      ),
                      child: Icon(
                        Icons.music_note,
                        size: 60,
                        color: Theme.of(context).primaryColor,
                      ),
                    ),
                  ),

                  const SizedBox(height: 32),

                  // 应用名称
                  const Text(
                    '音乐播放器',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                    ),
                  ),

                  const SizedBox(height: 8),

                  // 版本信息
                  Text(
                    'v1.0.0',
                    style: TextStyle(
                      color: Colors.white.withOpacity(0.8),
                      fontSize: 16,
                    ),
                  ),

                  const SizedBox(height: 60),

                  // 初始化状态
                  if (_isInitializing) ...[
                    SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(
                          Colors.white.withOpacity(0.8),
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    Text(
                      _initializationStatus,
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.8),
                        fontSize: 14,
                      ),
                    ),
                  ],
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
